/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.classes.Chat;
import org.classes.CommonUtils;
import org.classes.Conference;
import org.classes.Join;
import org.classes.Talk;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 *
 * @author marc
 */
public class ConferenceServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ServletContext context = getServletContext();
        CommonUtils.URL_DATABASE=context.getInitParameter("URL_DATABASE");
        CommonUtils.PORT_DATABASE=Integer.parseInt(context.getInitParameter("PORT_DATABASE"));
        CommonUtils.BBBCONFERENCE_KEYSPACE=context.getInitParameter("BBBCONFERENCE_KEYSPACE");
    }
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        PrintWriter out = response.getWriter();
        try {
            String command_param=request.getParameter("command");
            
            if(command_param.equalsIgnoreCase("create")){
                response.setContentType("text/xml");

                String name_param=request.getParameter("name");
                String url_param=request.getParameter("url");
                String date_param=request.getParameter("date");

                Conference conf=new Conference(name_param, url_param, date_param);
                String message="";
                message=conf.save();
                Document dom=CommonUtils.parseXmlFile(url_param);
                parseXML(dom,conf,Join.JOIN_ACTIVITY);
                parseXML(dom,conf,Talk.TALK_ACTIVITY);
                parseXML(dom,conf,Chat.CHAT_ACTIVITY);

                out.println("<message>"+message+"</message>");
            }
            else if(command_param.equalsIgnoreCase("list")){
                response.setContentType("text/html");
                ArrayList<Conference> conf_list=Conference.list();
                out.println("<html>");
                out.println("<head>");
                out.println("<title>List Conferences sample</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Conferences Saved</h1>");
                out.println("<div>");
                for(int i=0;i<conf_list.size();i++){
                    Conference conf=conf_list.get(i);
                    out.println("<a href=\"ConferenceServlet?command=show&uuid="+conf.getUuid()+"\">"+conf.getName()+"</a>");
                    out.println("<br />");
                }
                out.println("</div>");
                out.println("</body>");
                out.println("</html>");
            }
            else if(command_param.equalsIgnoreCase("show")){
                String uuid_param=request.getParameter("uuid");
                out.println(Conference.getListByUUID(uuid_param));
            }
            
        } finally { 
            out.close();
        }
    }

    public void parseXML(Document dom,Conference conf, String obj){
        Element docEle = dom.getDocumentElement();

        // save activities
        NodeList nl = docEle.getElementsByTagName(obj);
        System.out.println(obj+": "+nl.getLength());
        if(nl != null && nl.getLength() > 0) {
                for(int i = 0 ; i < nl.getLength();i++) {
                        Element el = (Element)nl.item(i);
                        if(obj.equalsIgnoreCase(Join.JOIN_ACTIVITY)){
                            Join joinobj = getJoin(el);
                            joinobj.setBbbconference(conf);
                            joinobj.save();
                        }
                        else if(obj.equalsIgnoreCase(Talk.TALK_ACTIVITY)){
                            Talk talkobj = getTalk(el);
                            talkobj.setBbbconference(conf);
                            talkobj.save();
                        }
                        else if(obj.equalsIgnoreCase(Chat.CHAT_ACTIVITY)){
                            Chat chatobj = getChat(el);
                            chatobj.setBbbconference(conf);
                            chatobj.save();
                        }
                }
        }
    }

    public Join getJoin(Element elem) {
        Join obj=new Join();
        obj.setTime(elem.getAttribute("time"));
        obj.setUser(elem.getAttribute("user"));
        obj.setCidName(elem.getAttribute("cidName"));
        obj.setCidNumber(elem.getAttribute("cidNumber"));
        obj.setMuted(Boolean.parseBoolean(elem.getAttribute("muted")));
        obj.setTalking(Boolean.parseBoolean(elem.getAttribute("talking")));
        return obj;
    }

    public Talk getTalk(Element elem) {
        Talk obj=new Talk();
        obj.setUser(elem.getAttribute("user"));
        obj.setStart(elem.getAttribute("start"));
        obj.setEnd(elem.getAttribute("end"));
        return obj;
    }

    public Chat getChat(Element elem) {
        Chat obj=new Chat();
        obj.setTime(elem.getAttribute("start"));
        obj.setUser(elem.getAttribute("user"));
        obj.setMessage(elem.getFirstChild().getNodeValue());
        return obj;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
